package processing.test.mechaapp;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;

import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PFont;

public class AppTimer {
	private Method gameOver;
	private Timer timer;
	private PApplet applet;
	private int xPos, yPos, beginTime, limit, currentTime;
	private PFont font;
	private boolean direction, onWait;
	
	public final static boolean COUNT_DOWN = true;
	public final static boolean COUNT_UP = false;
	
	public AppTimer(PApplet app, String name, int x, int y){
		applet = app;
		xPos = x;
		yPos = y;
		font = applet.loadFont("Roboto-Bold-48.vlw");
		direction = true;
		onWait = false;
		
		try {
			gameOver = applet.getClass().getMethod(name);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
	}
	
	public void start(int timeLimit){
		currentTime = beginTime = 0;
		limit = currentTime+timeLimit;
		timer = new Timer();
		onWait = false;
		timer.scheduleAtFixedRate(new RemindTask(), 0, 1000);
	}
	
	public void stop(){
		timer.cancel();
	}
	
	public void pause(){
		onWait = true;
	}
	
	public void resume(){
		onWait = false;
	}
	
	public void setDirection(boolean direct){
		direction = direct;
	}
	
	public int getTime(){
		int current = currentTime - beginTime;
		
		if(direction)
			return limit - current;
		else
			return current;
			
	}
	
	public void addToLimit(int seconds){
		limit += seconds; 
	}
	
	class RemindTask extends TimerTask{
		//this method gets fired once every second
		public void run() {
			if(!onWait){
				int seconds, minutes;
				String string1 = "", string2 ="";
			
				currentTime++;
			
				seconds = getTime();
				minutes = seconds / 60;
				if ((seconds % 60) < 10 && minutes > 0) {
					string2 = "0" + (seconds % 60);
				} else {
					string2 = string2 + (seconds % 60);
				}

				if (minutes > 0) {
					string1 = string1 + minutes + ":" + string2;
				} else {
					string1 = string1 + string2;
				}
			
				applet.g.beginDraw();
				applet.fill(0);
				applet.noStroke();
				applet.rectMode(applet.CENTER);
				applet.fill(2,18,26);
				applet.rect(xPos, yPos-17, 200, 50);
				applet.fill(255);//change the color of the litte box here!
				applet.textFont(font);
				applet.textAlign(PConstants.CENTER);
				applet.text(string1, xPos, yPos);
				applet.g.endDraw();
			
				if(direction && (currentTime >= limit))
					try {
						gameOver.invoke(applet);
						timer.cancel();
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					}
			}
		}
		
	}

}
